import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import classnames from 'classnames'
import { useHistory } from 'react-router'
import { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { Dialog } from 'antd-mobile-v5'
import {
  getSuggestList,
  clearSuggestions,
  addSuggestList,
  clearHistories,
} from '@/store/actions/search'
import { RootState } from '@/store'
const Search = () => {
  const history = useHistory()
  // 搜索内容
  const [keyword, setkeyword] = useState('')
  // 是否显示搜索
  const [isSeaching, setIsSeaching] = useState(false)
  const display = useDispatch()
  const { suggestions, historys } = useSelector(
    (state: RootState) => state.search
  )
  const timeRef = useRef(-1)
  // 搜索文字高亮
  const highlight = (str: string, key: string) => {
    return str.replace(new RegExp(key, 'gi'), (match: string) => {
      return `<span style="color:red">${match}</span>`
    })
  }
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const text = e.target.value.trim()
    setkeyword(text)
    clearTimeout(timeRef.current)
    timeRef.current = window.setTimeout(() => {
      console.log('发起请求', text)
      if (text) {
        setIsSeaching(true)
        display(getSuggestList(text))
      } else {
        setIsSeaching(false)
      }
    }, 500)
  }
  // 清空搜索
  const onclose = () => {
    setkeyword('')
    setIsSeaching(false)
    display(clearSuggestions())
  }
  // 点击搜索
  const onsearch = (key: string) => {
    if (!key) return
    display(addSuggestList(key))
    history.push('/search/result?key=' + key)
  }
  const onCloseHistory = () => {
    Dialog.confirm({
      content: '是否要删除记录',
      onConfirm: function () {
        display(clearHistories())
      },
    })
  }
  useEffect(() => {
    return () => {
      clearTimeout(timeRef.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        className="navbar"
        onLeftClick={() => history.go(-1)}
        extra={
          <span className="search-text" onClick={() => onsearch(keyword)}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyword}
              onChange={(e) => onChange(e)}
            />

            {/* 清空输入框按钮 */}
            <Icon
              type="iconbtn_tag_close"
              className="icon-close"
              onClick={onclose}
            />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      <div
        className="history"
        style={{ display: isSeaching ? 'none' : 'block' }}
      >
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={onCloseHistory}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {historys.map((item, index) => {
            return (
              <span
                className="history-item"
                key={index}
                onClick={() => onsearch(item)}
              >
                {item}
                <span className="divider"></span>
              </span>
            )
          })}
        </div>
      </div>

      {/* 搜素建议结果列表 */}
      <div className={classnames('search-result', { show: isSeaching })}>
        {suggestions.map((item, index) => {
          return (
            <div
              className="result-item"
              key={index}
              onClick={() => onsearch(item)}
            >
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value"
                dangerouslySetInnerHTML={{ __html: highlight(item, keyword) }}
              ></div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default Search
